import {shallowEqual} from './shallowEqual';
import uniqueId from 'lodash/uniqueId';

export const genCheckUpdate=({
    check,
    update,
    log
})=>{
    let _oldData;
    let checkCount=0;
    let changeCount=0;
    return function({
        checkArgs=[],
        updateArgs=[]
    }={}){
        const oldData = _oldData;
        const newData = check.call(this,{
            oldData
        },...checkArgs);
        const isChange = !shallowEqual(oldData, newData);
        log&&log('checkChangeUpdate shallowEqual:',checkCount++,oldData,newData);
        if (isChange) {
            log&&log('checkChangeUpdate isChange:',changeCount++);
            _oldData = newData;
            update.call(this,newData, oldData,...updateArgs);
        }
    };
};

export const connectModel=function({
    namespace=uniqueId('attachModel_'),
    model,
    log,
    check=()=>{
        return model.getData();
    },
    update=()=>{
        log&&log('请调用更新方法');
    }
}={}){
    const checkUpdate=genCheckUpdate({
        check,
        update,
        log
    });
    const fn=()=>{
        checkUpdate.call(this);
    };
    model.onChange(namespace,fn);
    const cancel=()=>{
        model.offChange(namespace,fn);
    };
    return {
        cancel
    };
};
export default connectModel;